<template>
  <div class="data-manage">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
      <el-breadcrumb-item>数据管理</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="data-header">
      <div class="search-box">
        <el-input
          v-model="searchQuery"
          placeholder="搜索数据..."
          class="search-input"
          clearable
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="searchType" placeholder="搜索类型" class="search-type">
          <el-option label="名称" value="name" />
          <el-option label="地址" value="address" />
          <el-option label="创建时间" value="createTime" />
        </el-select>
      </div>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加数据
      </el-button>
    </div>

    <el-card class="data-card">
      <el-table
        :data="filteredData"
        style="width: 100%"
        v-loading="loading"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column prop="address" label="地址" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '活跃' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button
                type="primary"
                :icon="Edit"
                circle
                @click="handleEdit(scope.row)"
              />
              <el-button
                type="danger"
                :icon="Delete"
                circle
                @click="handleDelete(scope.row)"
              />
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑数据抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="drawerType === 'add' ? '添加数据' : '编辑数据'"
      size="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="drawer-form"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="formData.status"
            :active-value="'active'"
            :inactive-value="'inactive'"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            rows="4"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="drawer-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Edit, Delete, Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 数据列表
const dataList = ref([])
const loading = ref(false)
const searchQuery = ref('')
const searchType = ref('name')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 抽屉相关
const drawerVisible = ref(false)
const drawerType = ref('add')
const formRef = ref(null)
const formData = ref({
  name: '',
  address: '',
  status: 'active',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ]
}

// 过滤后的数据
const filteredData = computed(() => {
  let filtered = dataList.value
  if (searchQuery.value) {
    filtered = filtered.filter(item => {
      const value = item[searchType.value]
      return value && value.toString().toLowerCase().includes(searchQuery.value.toLowerCase())
    })
  }
  return filtered
})

// 获取数据列表
const fetchData = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/data', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        searchType: searchType.value,
        searchQuery: searchQuery.value
      }
    })
    if (response.data.code === 200) {
      dataList.value = response.data.data.list
      total.value = response.data.data.total
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error(error.response?.data?.message || '获取数据失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 处理添加
const handleAdd = () => {
  drawerType.value = 'add'
  formData.value = {
    name: '',
    address: '',
    status: 'active',
    description: ''
  }
  drawerVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  drawerType.value = 'edit'
  formData.value = { ...row }
  drawerVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这条数据吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await axios.delete(`/api/data/${row.id}`)
      if (response.data.code === 200) {
        ElMessage.success('删除成功')
        fetchData()
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  })
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response
        if (drawerType.value === 'add') {
          response = await axios.post('/api/data', formData.value)
        } else {
          response = await axios.put(`/api/data/${formData.value.id}`, formData.value)
        }
        
        if (response.data.code === 200) {
          ElMessage.success(drawerType.value === 'add' ? '添加成功' : '更新成功')
          drawerVisible.value = false
          fetchData()
        } else {
          ElMessage.error(response.data.message || (drawerType.value === 'add' ? '添加失败' : '更新失败'))
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.response?.data?.message || (drawerType.value === 'add' ? '添加失败' : '更新失败'))
      }
    }
  })
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.data-manage {
  padding: 20px;
}

.data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.search-type {
  width: 120px;
}

.data-card {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.drawer-form {
  padding: 20px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
}
</style> 